package com.example.scg.route.generator;

import com.example.scg.route.enums.FilterType;
import com.example.scg.route.enums.PredicateType;
import io.micrometer.core.instrument.util.StringUtils;
import javax.validation.constraints.NotNull;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.support.NameUtils;

/**
 * Name加Array参数类型的过滤器定义和断言定义（FilterDefinition&PredicateDefinition）生成器
 *
 * CreateTime: 2020-01-12
 *
 * @author HuangZhongHui
 **/
public class NameArrayGenerator {

  /**
   * 生成路由过滤器定义
   *
   * @param type 过滤器名称
   * @param orderedArgs 有序的参数数组
   * @return 路由过滤器定义
   */
  public static FilterDefinition createFilter(@NotNull FilterType type,
      @NotNull String... orderedArgs) {
    FilterDefinition definition = new FilterDefinition();
    definition.setName(type.name());
    for (int i = 0; i < orderedArgs.length; i++) {
      definition.addArg(NameUtils.generateName(i), orderedArgs[i]);
    }
    return definition;
  }

  /**
   * 生成断言定义
   *
   * @param type 断言名称
   * @param orderedArgs 有序的参数数组
   * @return 路由断言定义
   */
  public static PredicateDefinition createPredicate(@NotNull PredicateType type,
      @NotNull String... orderedArgs) {
    PredicateDefinition definition = new PredicateDefinition();
    definition.setName(type.name());
    int order = 0;
    for (String arg : orderedArgs) {
      if (StringUtils.isNotBlank(arg)) {
        definition.addArg(NameUtils.generateName(order++), arg);
      }
    }
    return definition;
  }
}
